package com.example.paopagation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
@Qualifier("a")
public class A {
    @Autowired
    private AMapper mapper;

    @Autowired
    private B b;

    /**
     * A抛出异常后，B也会回滚，因为他们是同个事务,即使A中将B抛出的异常catch掉也不行
     * @throws IOException
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
    public void required_required() throws IOException {
        mapper.insert_A();
        try{
            b.required();

        }catch (Exception e){

        }
//        throw new RuntimeException("RuntimeException");
    }

    /**
     * A抛出异常，B仍然会提交成功，如果B抛出异常，B肯定不成功，如果A不将该异常catch掉，A也会受影响
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
    public void required_required_new() throws Exception{
        mapper.insert_A();
        b.required_new();
        throw new RuntimeException("RuntimeException");
    }


    /**
     * A抛出异常，B不抛异常，AB都不会提交成功，反过来B抛出异常，AB也不会成功，因为返回save point的时候，返回的是一个异常，
     * 相当于A方法也抛出异常了,但是A可以选择catch掉这个异常
     *
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
    public void required__nested(){
        mapper.insert_A();
        try{
            b.nested();

        }catch (Exception e){

        }
//        throw new RuntimeException("RuntimeException");
    }


}
